package com.lsp.microarticle.article.task;

import com.lsp.microarticle.article.service.ArticleService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class ArticleTask {

    @Resource
    private ArticleService articleService;

    @Resource
    private RedissonClient redissonClient;

//    修改文章的点赞总数，对应的字段是article的like_num
//    "0 0 0 * * ?" 表示每天的凌晨一点执行定时任务
//    方便演示，本例中使用每分钟的第一秒执行任务
//    @Async
//    @Scheduled(cron = "0 0 0 * * ?")
    @XxlJob("articleTask")
    public void articleTask(){
        RLock lock = redissonClient.getLock("like:updateNum");
        try {
            if (lock.tryLock(0,0, TimeUnit.SECONDS)) {
                articleService.updateLikeNumBatch();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(lock.isLocked()){
                if(lock.isHeldByCurrentThread()){
                    lock.unlock();
                }
            }
        }
    }
}
